﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
using U9API.Pub;
using System.Data;
using U9API.JsonModel;
using Newtonsoft.Json;
using System.Reflection;

namespace U9API.APIHelper
{


    public class ARBillHead
    {
        public Int64 ID { get; set; }
        public string DocNo { get; set; }

        public string DocumentType { get; set; }

        public Int64 AccrueCust_Customer { get; set; }

        public Int64 AccrueCustSite_CustomerSite { get; set; }

        public int SrcBusinessType { get; set; }

        public int DocStatus { get; set; }

        public string Memo { get; set; }

        public bool IsTaxPrice { get; set; }

        public string TaxSchedule { get; set; }

        public string AccrueDate { get; set; }

        public string PostPeriod { get; set; }

        public Int64 Transactor { get; set; }

        public List<ARBillLine> ARBillLines { get; set; }

        public string TransactorName { get; set; }
        public Int64 Dept { get; set; }

        public string DeptCode { get; set; }
        public string TransactorCode { get; set; }
    }
    public class ARBillLine
    {
        public Int64 ID { get; set; }
        public int LineNum { get; set; }

        public Int64 Item_ItemID { get; set; }

        public Decimal PUAmount { get; set; }

        public Decimal TaxPrice { get; set; }

        public Decimal AROCMoney_NonTax{get;set;}

        public Decimal AROCMoney_GoodsTax { get; set; } 

        public Decimal AROCMoney_TotalMoney { get; set; }

       
        public decimal AROCMoneyBalance_TotalMoney { get; set; } 
        

        public Int64 SrcBillID { get; set; }
        public Int64 SrcBillLineID { get; set; }
        public string SrcBillNum { get; set; }
        public Int64 SrcBillSOID { get; set; }
        public Int64 SrcBillSOLineID { get; set; }
        public string SrcBillSONum { get; set; }

        public decimal NonTaxPrice { get; set; }

        public int SrcDocType { get; set; }

        public Int64 SrcShipID { get; set; }
        public Int64 SrcShipLineID { get; set; }
        public Int64 SrcRMAID { get; set; }
        public Int64 SrcRMALineID { get; set; }
        public Int64 SrcRecID { get; set; }
        public Int64 SrcRecLineID { get; set; }
    }
    public class ARBillQueryHelper : BaseHelper<JsonModel.ApiQuery>
    { 
        public List<U9API.DBHelper.Model.Customer> Resdatas { get; set; }
        public string result;



        private ARBillHead DataRowToHModel(DataRow row)
        {
            ARBillHead model = new ARBillHead();
            Type examType = typeof(ARBillHead);
            BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
            if (row != null)
            {
                DataColumnCollection dc = row.Table.Columns;
                for (int i = 0; i < dc.Count; i++)
                {
                    if (row[dc[i].ColumnName] != null && row[dc[i].ColumnName].ToString() != "")
                    {
                        PropertyInfo piInstance = examType.GetProperty(dc[i].ColumnName, flag);
                        if (piInstance != null)
                        {
                            piInstance.SetValue(model, row[dc[i].ColumnName], null);
                        }
                    }
                }
            }

            return model;
        }

        private ARBillLine DataRowToBModel(DataRow row)
        {
            ARBillLine model = new ARBillLine();

            Type examType = typeof(ARBillLine);
            BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
            if (row != null)
            {
                DataColumnCollection dc = row.Table.Columns;
                for (int i = 0; i < dc.Count; i++)
                {
                    if (row[dc[i].ColumnName] != null && row[dc[i].ColumnName].ToString() != "")
                    {
                        PropertyInfo piInstance = examType.GetProperty(dc[i].ColumnName, flag);
                        if (piInstance != null)
                        {
                            piInstance.SetValue(model, row[dc[i].ColumnName], null);
                        }
                    }
                }
            }
            return model;
        }


        protected override void Create(string U9constr, int operation, List<JsonModel.ApiQuery> models )
        {
            //Pub.WriteLog.WriteLine(DateTime.Now.ToShortDateString() + ": CustomerHelper");
            if (models.Count == 0)
            {
                throw new Exception("查询条件不允许为空!");
            }
            JsonModel.ApiQuery model = models[0];
            StringBuilder sql = new StringBuilder();
            sql.Append("select A7.Code as TransactorCode, A8.Code as DeptCode,  A.Transactor, A.Dept as DeptCode, A.ID, A.DocNo, A3.Name as DocumentType, A6.Name as TransactorName, A.AccrueCust_Customer, A.AccrueCustSite_CustomerSite, A.SrcBusinessType, A.DocStatus, A1.Memo , A.IsTaxPrice, A4.Code as TaxSchedule, Convert(varchar(10), AccrueDate,121) as AccrueDate, DisplayName as PostPeriod ");
            sql.Append(" from AR_ARBillHead as A  left join[AR_ARBillHead_Trl] as A1 on(A1.SysMlFlag = 'zh-CN') and(A.[ID] = A1.[ID]) ");
            sql.Append(" left join Base_SOBAccountingPeriod A2 on A2.ID = A.PostPeriod ");
            sql.Append(" left join CBO_TaxSchedule A4 ON A4.ID = A.TaxSchedule "); 
            sql.Append(" LEFT JOIN CBO_Operators_Trl A6 ON A6.ID = A.Transactor");
            sql.Append(" LEFT JOIN CBO_Operators A7 ON A7.ID = A.Transactor ");
            sql.Append(" LEFT JOIN CBO_Department A8 on A8.ID = A.Dept");
            sql.Append(" left join AR_ARDocType_Trl A3 on A3.ID = A.DocumentType WHERE 1=1  "); 

            if (!string.IsNullOrEmpty(model.code))
            {
                sql.Append("and A.DocNo = '" + model.code + "'");
            }
            if (!string.IsNullOrEmpty(model.id))
            {
                sql.Append("and A.ID = '" + model.id + "'");
            }
            if (!string.IsNullOrEmpty(model.customer))
            {
                sql.Append("and A.AccrueCust_Customer = '" + model.customer + "'");
            }
            if (!string.IsNullOrEmpty(model.startdate))
            {
                sql.Append(" and (A.CreatedOn >='" + model.startdate + "' or A.ModifiedOn >='" + model.startdate +"')");
            }
            if (!string.IsNullOrEmpty(model.enddate))
            {
                sql.Append(" and (A.CreatedOn <='" + model.enddate + "' or A.ModifiedOn <='" + model.enddate + "')");
            }
            DataSet ds = DbHelperSQL.Query(sql.ToString(), U9constr);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            { 
                List<ARBillHead> mlist = new List<ARBillHead>();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    mlist.Add(this.DataRowToHModel(ds.Tables[0].Rows[i]));
                }

                foreach (var item in mlist)
                {
                    StringBuilder sqlb = new StringBuilder();
                    sqlb.Append("  select ID, LineNum, Item_ItemID, PUAmount, TaxPrice, AROCMoney_NonTax, AROCMoney_GoodsTax, AROCMoney_TotalMoney,SrcBillSOID, SrcBillSOLineID, SrcBillSONum, SrcBillNum, AROCMoneyBalance_TotalMoney, NonTaxPrice, SrcBillID, SrcBillLineID, SrcDocType from AR_ARBillLine Where AR_ARBillLine.ARBillHead = '" + item.ID + "' ");
                    //Pub.WriteLog.WriteLine(sql.ToString());

                    DataTable dtb = DbHelperSQL.QueryAsDT(sqlb.ToString(), U9constr);
                    if (dtb != null && dtb.Rows.Count > 0)
                    {
                        item.ARBillLines = new List<ARBillLine>();
                        for (int i = 0; i < dtb.Rows.Count; i++)
                        {
                            ARBillLine body = this.DataRowToBModel(dtb.Rows[i]);
                            if (body.SrcDocType == 1)
                            {
                                body.SrcShipID = body.SrcBillID;
                                body.SrcShipLineID = body.SrcBillLineID;
                            }
                            else if(body.SrcDocType == 2)
                            {
                                body.SrcRMAID = body.SrcBillID;
                                body.SrcRMALineID = body.SrcBillLineID;
                            }
                            else if (body.SrcDocType == 11)
                            {
                                body.SrcRecID = body.SrcBillID;
                                body.SrcBillLineID = body.SrcBillLineID;
                            }
                            item.ARBillLines.Add(body);
                        }
                    }
                }
                result = mlist.ToJson();
            }
            else
            {
                throw new Exception("没有查到匹配的应收记录!");
                
            }
        }
         
    }
}
